package controller.admin;

import controller.Items.course;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import sample.Admin.AdminAddCourse;
import sql.JDBC_T;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.Vector;
import java.util.regex.Pattern;


public class AdminCourseController {
    @FXML
    private TextField adm_txfld_search;
    @FXML
    private TableView adm_tblList_course;
    @FXML
    private Button adm_btn_addcourse;

    private Alert alertwindow;
    private AnchorPane anchorPane;
    private TableView tableView;
    private JDBC_T jdbc_t;


    public void initialize() throws Exception {
       update(this.adm_tblList_course);

    }
    public void update(TableView tableView)throws Exception{
        String sql = "SELECT course.CID,course.Cname,course.TID,course.Ctime,course.Classroom\n" +
                "FROM course\n" +
                "GROUP BY course.CID;";
        JDBC_T jdbc_t = new JDBC_T();
        String cid,cname,tid,ctime,classroom;
        ObservableList<course> courses = FXCollections.observableArrayList();
        Vector<String> ids = new Vector<>();
        if (jdbc_t.is_conn()){
            System.out.println("查询课程成功!!!");
            PreparedStatement preparedStatement = jdbc_t.getConn().prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            while(resultSet.next()){
                cid=resultSet.getString("CID");
                cname = resultSet.getString("Cname");
                tid =resultSet.getString("TID");
                ctime = resultSet.getString("Ctime");
                classroom =resultSet.getString("Classroom");
                courses.add(new course(cid,cname,tid,ctime,classroom));
                ids.add(cid);
            }
            ObservableList<TableColumn> cols=tableView.getColumns();
            TableColumn CID= cols.get(0);
            TableColumn CNAME = cols.get(1);
            TableColumn  TID = cols.get(2);
            TableColumn  CTIME = cols.get(3);
            TableColumn  CLASSROOM = cols.get(4);
            TableColumn edit = cols.get(5);
            CID.setCellValueFactory(new PropertyValueFactory<>("cid"));
            CNAME.setCellValueFactory(new PropertyValueFactory<>("cname"));
            TID.setCellValueFactory(new PropertyValueFactory<>("tid"));
            CTIME.setCellValueFactory(new PropertyValueFactory<>("ctime"));
            CLASSROOM.setCellValueFactory(new PropertyValueFactory<>("classroom"));


            //控件

            TableColumn modify = (TableColumn) edit.getColumns().get(0);
            TableColumn delete = (TableColumn) edit.getColumns().get(1);
            modify.setCellFactory((col) -> {TableCell<course,String> cell = new TableCell<course,String>(){
                @Override
                protected void updateItem(String item, boolean empty) {
                    super.updateItem(item,empty);
                    Button button = new Button("修改");
                    button.setOnAction((col) -> {
                    String sql = "";
                    course cou = courses.get(getIndex());
                    if (ids.contains(cou.getCid())) {
                        sql = MessageFormat.format("update course  set  Cname={0}{1}{0},TID={0}{2}{0},Ctime={0}{3}{0},Classroom={0}{4}{0}"
                        +"\nwhere CID={0}{5}{0}",'"',cou.getCname(),cou.getTid(),cou.getCtime(),cou.getClassroom(),cou.getCid());
                    System.out.println(sql);
                    try {
                    preparedStatement.execute(sql);
                    }catch (SQLException sqlException) {
                        sqlException.printStackTrace();
                    }
                    }else {
                        alertwindow = new Alert(Alert.AlertType.WARNING);
                        alertwindow.setContentText("请注意是否修改了id");
                        alertwindow.showAndWait();
                    }
                }
                );
                if (empty) {
                    setText(null);
                    setGraphic(null);}
                else
                { this.setGraphic(button); }
            }
        };
        return cell;
        });
        delete.setCellFactory((col) -> {TableCell<course,String> cell = new TableCell<course, String>() {
            @Override
            protected  void updateItem(String item, boolean empty) {
                super.updateItem(item,empty);
                Button button = new Button("删除");
                button.setOnAction((col) -> {
                    System.out.println(getIndex());
                    course delcou = courses.get(getIndex());
                    String cid1 = delcou.getCid();
                    String sql1 = MessageFormat.format("Delete from course where CID={0}{1}{0}",'"',cid1);
                    try {
                        preparedStatement.execute(sql1);
                    } catch (SQLException sqlException) {
                        sqlException.printStackTrace();
                    }
                    System.out.println(sql1);
                    courses.remove(delcou);
                });
                if (empty) {
                    setText(null);
                    setGraphic(null);
                }else { this.setGraphic(button); }
            }
        };
        return cell;
        });
        tableView.setItems(courses);
        tableView.setEditable(true);
        CID.setCellFactory(TextFieldTableCell.forTableColumn());
        CNAME.setCellFactory(TextFieldTableCell.forTableColumn());
        TID.setCellFactory(TextFieldTableCell.forTableColumn());
        CTIME.setCellFactory(TextFieldTableCell.forTableColumn());
        CLASSROOM.setCellFactory(TextFieldTableCell.forTableColumn());
        }
    }
    public  void search() throws SQLException {
        Alert alertwindow;
        AnchorPane anchorPane;
        TableView tableView;
        Stage newstage = new Stage();
        anchorPane =new AnchorPane();
        tableView = new TableView();
        String search = adm_txfld_search.getText();
        String cid,cname,tid,ctime,classroom;
        ObservableList<course>result= FXCollections.observableArrayList();
        TableColumn Cid,Cname,Tid,Ctime,Classroom;
        Cid = new TableColumn<>("Cid");
        Cname= new TableColumn<>("Cname");
        Tid= new TableColumn<>("Tid");
        Ctime = new TableColumn<>("Ctime");
        Classroom = new TableColumn<>("Classroom");
        Cid.setCellValueFactory(new PropertyValueFactory<>("Cid"));
        Cname.setCellValueFactory(new PropertyValueFactory<>("Cname"));
        Tid.setCellValueFactory(new PropertyValueFactory<>("Tid"));
        Ctime.setCellValueFactory(new PropertyValueFactory<>("Ctime"));
        Classroom.setCellValueFactory(new PropertyValueFactory<>("Classroom"));
        tableView.getColumns().addAll(Cid,Cname,Tid,Ctime,Classroom);
        ObservableList<course> courses = this.adm_tblList_course.getItems();
        String reg1 = "\\d{1,5}";
        String reg2 ="[\\u4e00-\\u9fa5]{1,4}";
        alertwindow=new Alert(Alert.AlertType.WARNING);
        if(search.isEmpty()){
            alertwindow.setContentText("请输入内容");
            alertwindow.showAndWait();
        }
        else if(Pattern.matches(reg1,search)){
            for(course i : courses){
                if(i.getCid().equals(search)){
                    result.add(i);
                }
            }
            if(result.isEmpty()){
                alertwindow.setContentText("没有搜索到此课程");
                alertwindow.showAndWait();
            }else {
                anchorPane.setPrefWidth(300);
                anchorPane.setPrefHeight(300);
                tableView.setItems(result);
                anchorPane.getChildren().add(tableView);
                Scene scene = new Scene(anchorPane);
                newstage.setScene(scene);
                newstage.show();
            }
        }
        else if(Pattern.matches(reg2,search)){
            for(course i : courses){
                if(i.getCname().equals(search)){
                    result.add(i);
                }
            }
            if(result.isEmpty()){
                alertwindow.setContentText("没有搜索到此课程");
                alertwindow.showAndWait();
            }else {
                anchorPane.setPrefWidth(300);
                anchorPane.setPrefHeight(300);
                tableView.setItems(result);
                anchorPane.getChildren().add(tableView);
                Scene scene = new Scene(anchorPane);
                newstage.setScene(scene);
                newstage.show();
            }
        }
        else{
            alertwindow.setContentText("请检查输入");
            alertwindow.showAndWait();
        }
    }
    public void addcourse() throws Exception {
        new AdminAddCourse().start(new Stage());
    }

}
